﻿using AutoMapper;
using NetTaste;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using VM.Common.DataUntil;
using VM.Common.Result;
using VM.Entity.EntityMap.Member;
using VM.Entity.EntityMap.OAuth;
using VM.Entity.EntityMap.People;
using VM.Entity.EntityMap.System.Code;
using VM.Entity.EntityMap.Token;
using VM.Entity.EntityMap.Topic;
using VM.Entity.EntityMap.User;
using VM.IDAL.OAuth;
using static Dm.parser.LVal;

namespace VM.DAL.OAuth
{
    public class OAuthDAL : BaseDAL, IOAuthDAL
    {

        protected ISqlSugarClient _Client { get; set; }
        protected IMapper _IMapper { get; set; }


        public OAuthDAL(ISqlSugarClient client, IMapper iMapper) : base(client)
        {
            _Client = client;
            _IMapper = iMapper;
        }



        /// <summary>
        /// ApiDataResult<sys_refreshToken> addRefreshToken(sys_refreshToken obj)
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public ApiDataResult<sys_refreshToken> checkRefreshToken(RefreshTokenDataEntity obj)
        {
            long? datatimeNow= Timestamp.getNowTimeStamp();

          List<sys_refreshToken> listRes = _Client.Queryable<sys_refreshToken>()
         .Where(a => a.refreshKey == obj.refresh_token)
         .Where(a => a.endDateTimes >= datatimeNow)
      
         .Where(a => a.userId == obj.userId)
         .ToList();
            if (listRes.Count == 1)
            {
                sys_refreshToken resInfo= listRes[0];
                ApiDataResult<sys_refreshToken> res = new ApiDataResult<sys_refreshToken>()
                {
                    code = 200,
                    msg = "可用",
                    data = resInfo
                };
                return res;

            }
            else
            {
                ApiDataResult<sys_refreshToken> res = new ApiDataResult<sys_refreshToken>()
                {
                    code = 403,
                    msg = "鉴权已过期",
                    data = null

                };
                return res;
            }



        }

        public int  addRefreshToken(sys_refreshToken obj)
        {
            int  Res = _Client.Insertable(obj)
                .ExecuteCommand();
           return Res;
        }
        /// <summary>
        /// 刷新token
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public int  refreshRefreshToken(sys_refreshToken obj)
        {
            int Res = _Client.Updateable(obj)
                .UpdateColumns(it => new { it.endDateTimes,it.refreshDateTimes})
                .Where(it=>it.refreshKey==obj.refreshKey)
                .Where(it => it.userId == obj.userId)
              .ExecuteCommand();
            return Res;


        }
    }
}
